<template>
  <div>
    <div class="tips" v-if="$store.state.session.user.type === 'agent'">{{$t('monitor.tips2')}}</div>
    <div v-show="!isActive" class="wrap">
      <affix :label="$t('monitor.dataSummary')" :bodyStyle="{paddingTop:'30px'}" >
      <span slot="questionSlot">
        <span class="tip" @click.stop="detail">{{$t('monitor.clickDetail')}}</span>
      </span>
        <el-row :gutter="10">
            <el-col :span="8" class="position-re">
              <square-detail :data="showData[0]" :num="summary" :tooltip="{width:450, content:$t('monitor.tooltipChat0')}"></square-detail>
            </el-col>
            <el-col :span="8" class="position-re">
              <square-detail :data="showData[1]" :num="summary" :tooltip="{width:350, content:$t('monitor.tooltipChat1')}"></square-detail>
            </el-col>
            <el-col :span="8" class="position-re">
              <square-detail :data="showData[2]" :num="summary" :tooltip="{width:480, content:$t('monitor.tooltipChat2')}"></square-detail>
            </el-col>
            <el-col :span="8" class="position-re">
              <square-detail :data="showData[3]" :num="summary" :tooltip="{width:250, content:$t('monitor.tooltipChat3')}"></square-detail>
            </el-col>
            <el-col :span="8" class="position-re">
              <square-detail :data="showData[4]" :num="webchatAgentStatus" :tooltip="{width:380, content:$t('monitor.tooltipChat4')}"></square-detail>
            </el-col>
            <el-col :span="8" class="position-re">
              <square-detail :data="showData[5]" :num="webchatAgentStatus" :tooltip="{width:450, content:$t('monitor.tooltipChat5')}"></square-detail>
            </el-col>
        </el-row>
      </affix>
      <affix :label="$t('monitor.webchatAgentMonitor')" :bodyStyle="{paddingTop:'30px'}">
        <el-form ref="form" :model="form" label-position="left" :inline="true">
          <el-form-item :label="$t('public.agent')">
            <search
              module="chat"
              power="chat"
              @change="agentSearch"
              ref="searchAgent"
            ></search>
          </el-form-item>
          <br>
          <el-form-item :label="$t('monitor.busyType')">
            <el-select size="mini" v-model="form.login" collapse-tags @change="stateChange" :placeholder="$t('public.pleasePick')" filterable :multiple="true" class="width-full">
              <el-option
                v-for="(item,index) in allState"
                :label="item.value"
                :key="index"
                value-key="_id"
                :value="item.key">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('monitor.getState')">
            <el-select size="mini" v-model="form.state" collapse-tags @change="stateChange" :placeholder="$t('public.pleasePick')" filterable :multiple="true" class="width-full">
              <el-option
                v-for="(item,index) in allGet"
                :label="item.value"
                :key="index"
                value-key="_id"
                :value="item.key">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div class="clearBoth config">
          <el-button class="fr" size="small" @click="config" v-if="configHeaderShow">{{$t('monitor.setHeaderConfig')}}</el-button>
        </div>
        <table-agent :allList="searchAgent"
                     class="monitor-table"
                     :header="monitorHeader"
                     :cacheAgent="cacheAgent"
        ></table-agent>
      </affix>
      <header-option :show="isShow" :option="headOptionsShow"  :noDrag="headOptionsNoShow" type="monitor_agent_multi" v-on:close="close"></header-option>
    </div>
    <keep-alive>
      <component :is="isActive" @back="back"></component>
    </keep-alive>
  </div>
</template>
<script>
  import Affix from '../../ui-modules/affix/Affix'
  import squareDetail from './base/squareDetail'
  import headerOption from '../report/base/headerOption.vue'
  import search from './base/AgentSearch'
  import webchatData from './webchatDataCompare'
  import tableAgent from './base/tableAgentIm'
  import bus from '@/store/eventBus'
import { filter } from 'vuedraggable'
  export default {
    name: 'callMonitor',
    data () {
      return {
        form: {
          login: [], // 登陆状态
          state: [] // 领取状态
        },
        cacheAgent: [],
        showData: [
          {
            main: {value: 'allSession', name: this.$t('monitor.sessionNumToday')},
            sub: [{value: 'accessSession', name: this.$t('monitor.agentManual')}, {value: 'closeSession', name: this.$t('monitor.sessionNumTodayAnswer')}]
          },
          {
            main: {value: 'dealingSession', name: this.$t('monitor.dealingSession')},
            sub: [{value: 'imDealCount', name: this.$t('monitor.imDealCount')}]
          },
          {
            main: {value: 'waitClaim', name: this.$t('monitor.waitingSessionNum'), type: 'red'},
            sub: [
              {value: 'undealSession', name: this.$t('monitor.unAccessSession'), type: 'red'},
              {value: 'queueGiveupCount', name: this.$t('monitor.queuingLeak'), type: 'red'}
            ]
          },
          {
            main: {value: 'messageSession', name: this.$t('monitor.messageSession')},
            sub: []
          },
          {
            main: {value: 'online', name: this.$t('monitor.onlineAgent')},
            sub: [
              {value: 'open', name: this.$t('monitor.onlineAgentNum')}, 
              {value: 'close', name: this.$t('monitor.offlineAgentNum')},
              {value: 'customizeStatus', name: this.$t('monitor.customizeAgentNum')}
            ]
          },
          {
            main: {value: 'free', name: this.$t('monitor.idleAgent')},
            sub: [{value: 'busy', name: this.$t('monitor.sessionBusyAgent')}]
          }
        ],
        allState: [
          {
            key: 'pcState:1',
            value: this.$t('monitor.agentOline', {name: 'PC'})
          },
          {
            key: 'mobileState:1',
            value: this.$t('monitor.agentOline', {name: 'APP'})
          },
          {
            key: 'pcState:0',
            value: this.$t('monitor.agentOffline', {name: 'PC'})
          },
          {
            key: 'mobileState:0',
            value: this.$t('monitor.agentOffline', {name: 'APP'})
          }
        ],
        allGet: [
          {
            key: 'pcAutoStatus:1',
            value: this.$t('monitor.webOnline', {name: 'PC'})
          },
          {
            key: 'pcAutoStatus:0',
            value: this.$t('monitor.webOffline', {name: 'PC'})
          },
          {
            key: 'mobileAutoStatus:1',
            value: this.$t('monitor.agentOpen', {name: 'APP'})
          },
          {
            key: 'mobileAutoStatus:0',
            value: this.$t('monitor.agentClose', {name: 'APP'})
          },
          {
            key: 'mailAutoStatus:1',
            value: this.$t('monitor.agentOpen', {name: this.$t('public.mail')})
          },
          {
            key: 'mailAutoStatus:0',
            value: this.$t('monitor.agentClose', {name: this.$t('public.mail')})
          }
        ],
        currentStateCondition: {},
        isActive: '',
        headOptionsShow: {},
        scope: 'noScope',
        isShow: false,
        monitorHeader: [],
        headOptionsNoShow: [
          {'name': 'agentName', displayname: this.$t('public.agent'), 'order': 1, 'show': true},
          {'name': 'agentNo', displayname: this.$t('public.jobNumber'), 'order': 2, 'show': true}
        ]
      }
    },
    props: {
    },
    components: {
      Affix,
      squareDetail,
      search,
      webchatData,
      headerOption,
      tableAgent
    },
    inject: ['webchatPeers', 'init', 'configHeaderShow'],
    computed: {
      summary () {
        return this.$store.state.monitor.webchatSummary
      },
      webchatAgentStatus () {
        let agentStatus = this.$store.state.monitor.webchatAgentStatus
        let {offline, close, free, busy, customize} = agentStatus
        let online = close + free + busy + customize
        let open = free + busy
        let customizeStatus = customize
        return {offline, online, close, open, free, busy, customizeStatus}
      },
      // 显示坐席总数
      searchAgent () {
        let cacheAgent = this.cacheAgent
        let arr = []
        cacheAgent.forEach(item => {
          if (item.show) {
            arr.push(item._id)
          }
        })
        return arr
      }
    },
    methods: {
      back () {
        this.isActive = ''
        bus.$emit('monitor:callMonitorRefresh')
      },
      detail () {
        this.isActive = 'webchatData'
      },
      // 坐席组件change事件
      agentSearch ({type, leaf, includeSubordinate}) {
        this.cacheAgent = leaf.map(item => {
          return {_id: item, show: true}
        })
        if (includeSubordinate) {
          // 我和我的下属
          let agentList = this.$refs.searchAgent.allAgent
          let getAgent = function (pid) {
            for (var i = 0; i < agentList.length; i++) {
              var obj = agentList[i]
              if (obj.parentId &&
                obj.parentId === pid) {
                if (!this.cacheAgent.some(item => item._id === obj._id)) {
                  this.cacheAgent.push({_id: obj._id, show: true})
                }
                getAgent.call(this, obj._id)
              }
            }
          }
          this.cacheAgent.map((item) => {
            getAgent.call(this, item._id)
          })
        }
        this.search()
      },
      // 坐席状态change事件,生成当前状态条件
      stateChange () {
        let filterLogin = {}
        let filterState = {}
        this.form.login.forEach((item) => {
          let _state = item.split(':')
          if (filterLogin[_state[0]] === undefined) {
            filterLogin[_state[0]] = parseInt(_state[1])
          } else {
            delete filterLogin[_state[0]]
          }
        })
        this.form.state.forEach((item) => {
          let _state = item.split(':')
          if (filterState[_state[0]] === undefined) {
            filterState[_state[0]] = parseInt(_state[1])
          } else {
            delete filterState[_state[0]]
          }
        })
        console.log(filterState)
        this.currentStateCondition = Object.assign({}, filterLogin, filterState)
        this.search()
      },
      search () {
        this.cacheAgent.forEach((item) => {
          // 根据条件，确定该坐席是否展示
          item.show = this.filterCondition(item._id)
        })
      },
      // 状态条件
      filterCondition (_id) {
        let isTrue = true
        let _agent = this.webchatPeers[_id] || {}
        for (let i in this.currentStateCondition) {
          if (_agent[i] !== this.currentStateCondition[i]) {
            isTrue = false
            break
          }
        }
        return isTrue
      },
      config () {
        this.$store.dispatch('getReportTableHeader', 'monitor_agent_multi').then((res) => {
          res.Config.splice(0, 2)
          this.headOptionsShow = res
          this.isShow = !this.isShow
        })
      },
      close (data) {
        this.isShow = false
        if (data === 'save') {
          this.$store.dispatch('getImMonitorTableHeader', 'monitor_agent_multi').then((res) => {
            res.Config.splice(0, 2)
            this.monitorHeader = res.Config
          })
        }
      },
      agentChangeEvt (peer) {
        this.cacheAgent.some((item, index) => {
          if (item._id === peer) {
            this.cacheAgent[index].show = this.filterCondition(item._id)
            return true
          }
        })
      }
    },
    activated () {
      // 激活时，坐席详情需要刷新和重新计算高度
      bus.$emit('monitor:imMonitorRefresh')
    },
    beforeMount () {
      this.init('webchatInit')
      this.close('save')
      // this.$store.dispatch('queryEnableWebStatus', {}).then((res) => {
      //   if (res.success && res.isEnableWebStatus) {
      //     let newData = []
      //     res.data.forEach(item => {
      //       newData.push({value: 'PC' + item.webStatusName, key: 'customizeStatus:' + item.webStatusName})
      //     })
      //     this.allGet = this.allGet.concat(newData)
      //   }
      // })
      // 在线咨询坐席事件
      bus.$on('monitor:agentChangeIm', this.agentChangeEvt)
    },
    beforeDestroy () {
      bus.$off('monitor:agentChangeIm', this.agentChangeEvt)
    }
  }
</script>
<style lang="stylus" scoped>
  @import '../../../assets/common.styl';
  .wrap
    padding 20px
    .tip
      color $c-main
      cursor pointer
      font-size 12px
      font-weight normal
  .position-re
    position relative
  .tooltip-span
    position absolute
    right 10px
    top 10px
  .icon-tixingweizhi
    border: 1px solid $c-main
    border-radius: 50%
    display: inline-block
    height: 16px
    width: 16px
    text-align: center
    line-height: 16px
    font-size: 10px
    color $c-main
    margin 0 5px
  .config
    padding-bottom 10px
  .tips
    padding 20px 0 0 20px
    color $c-prompt
  .width-full
    width 220px
    margin-right 10px
  .label-name
    display inline-block
    padding-right 20px
    margin-bottom 4px
</style>
